package com.xinqi.modules.course.textbook.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.course.chapter.domain.CourseChapterEntity;
import com.xinqi.modules.course.chapter.mapper.CourseChapterMapper;
import com.xinqi.modules.course.textbook.dto.req.CourseCloudTextbookContentCreateDTO;
import com.xinqi.modules.course.textbook.dto.req.CourseCloudTextbookContentDeleteDTO;
import com.xinqi.modules.course.textbook.dto.req.CourseCloudTextbookContentQueryDTO;
import com.xinqi.modules.course.textbook.dto.req.CourseCloudTextbookContentUpdateDTO;
import com.xinqi.modules.course.textbook.dto.rsp.CourseCloudTextbookContentResultDTO;
import com.xinqi.modules.course.textbook.convert.CourseCloudTextbookContentConvert;
import com.xinqi.modules.course.textbook.domain.CourseCloudTextbookContentEntity;
import com.xinqi.modules.course.textbook.manager.CourseCloudTextbookContentManager;
import com.xinqi.modules.course.textbook.service.CourseCloudTextbookContentService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 课程模块云课本课堂内容服务层实现
 *
 * @author: wenjie
 * @date: 2023/05/30
 */
@Validated
@Service("courseCloudTextbookContentService")
@RequiredArgsConstructor
public class CourseCloudTextbookContentServiceImpl implements CourseCloudTextbookContentService {
    private final CourseCloudTextbookContentConvert courseCloudTextbookContentConvert;
    private final CourseCloudTextbookContentManager courseCloudTextbookContentManager;
    private final CourseChapterMapper courseChapterMapper;

    /**
     * 分页查询 课程模块云课本课堂内容数据
     */
    @Override
    @DS("slaver")
    public PageInfo<CourseCloudTextbookContentResultDTO> page(Param pageable, CourseCloudTextbookContentQueryDTO query) {
        IPage<CourseCloudTextbookContentEntity> page = courseCloudTextbookContentManager.page(Pages.page(pageable), wrapper(query));
        PageInfo<CourseCloudTextbookContentResultDTO> pages = Pages.convert(page, courseCloudTextbookContentConvert::convert);

        CourseChapterEntity chapterEntity = courseChapterMapper.selectById(query.getRefId());
        if (CollectionUtils.isNotEmpty(pages.getRows())) {
            pages.getRows().forEach(record -> record.setChapterName(chapterEntity.getName()));
        }
        return pages;
    }

    /**
     * 查询 课程模块云课本课堂内容数据
     */
    @Override
    public List<CourseCloudTextbookContentResultDTO> find(CourseCloudTextbookContentQueryDTO query) {
        return courseCloudTextbookContentManager.list(wrapper(query)).stream()
                .map(courseCloudTextbookContentConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<CourseCloudTextbookContentEntity> wrapper(CourseCloudTextbookContentQueryDTO query) {
        LambdaQueryWrapper<CourseCloudTextbookContentEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(CourseCloudTextbookContentEntity::getId, v));
        Queries.accept(query.getRefId(), v -> wrapper.eq(CourseCloudTextbookContentEntity::getRefId, v));
        wrapper.orderBy(true, true, CourseCloudTextbookContentEntity::getPageNum);
        return wrapper;
    }

    /**
     * 根据id查询 课程模块云课本课堂内容数据
     */
    @Override
    public CourseCloudTextbookContentResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(courseCloudTextbookContentManager.findById(id)).map(courseCloudTextbookContentConvert::convert).orElse(null);
    }

    /**
     * 新增 课程模块云课本课堂内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid CourseCloudTextbookContentCreateDTO dto) {
        CourseCloudTextbookContentEntity entity = courseCloudTextbookContentConvert.create(dto);
        courseCloudTextbookContentManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 课程模块云课本课堂内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid CourseCloudTextbookContentUpdateDTO dto) {
        Optional.ofNullable(courseCloudTextbookContentManager.getById(dto.getId()))
                .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        CourseCloudTextbookContentEntity entity = courseCloudTextbookContentConvert.update(dto);
        return courseCloudTextbookContentManager.updateById(entity);
    }

    /**
     * 根据id删除 课程模块云课本课堂内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return courseCloudTextbookContentManager.removeById(id);
    }

    /**
     * 根据id删除 课程模块云课本课堂内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(CourseCloudTextbookContentDeleteDTO dto) {
        return deleteById(dto.getId());
    }

}
